<template>
    <div style="height: 100%">
        <el-container style="height: 99.8%">
            <el-aside width="200px;height: 100%">
                <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                    <el-col :span="24">
                        <span style="font-size: 20px; font-weight: 1000; color: white">
                            <el-icon><HomeFilled /></el-icon>{{ $t('功能列表') }}
                        </span>
                    </el-col>
                </el-row>
                <el-card style="height: 94%; width: 99%">
                    <el-scrollbar height="100%">
                        <div>
                            <el-input v-model="filterText" :suffix-icon="Search" :placeholder="$t('请输入')">
                                <template #append>
                                    <el-dropdown>
                                        <span>
                                            <el-icon><MoreFilled /></el-icon>
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item @click="expandAll">{{ $t('展开') }}</el-dropdown-item>
                                                <el-dropdown-item @click="collapseAll">{{ $t('收缩') }}</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </template>
                            </el-input>
                            <el-divider style="margin: 5px" />
                            <!-- prettier-ignore -->
                            <el-tree style="max-width: 400px" 
                            ref="treeRef" 
                            :data="treedata" 
                            :props="defaultProps" 
                            default-expand-all 
                            :expand-on-click-node="false" 
                            :filter-node-method="filterNode" 
                            highlight-current 
                            @node-click="handleNodeClick">
                              <template #default="{ node, data }">
                                  <span>
                                      <div v-if="node.isCurrent">
                                          <span style="color: blue">{{ $t(node.label) }}</span>
                                      </div>
                                      <div v-else>
                                          <span>{{ $t(node.label) }}</span>
                                      </div>
                                  </span>
                              </template>
                          </el-tree>
                        </div>
                    </el-scrollbar>
                </el-card>
            </el-aside>
            <el-main style="padding: 0; overflow: hidden">
                <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                    <el-col :span="4">
                        <span style="font-size: 20px; font-weight: 1000; color: white"
                            ><el-icon><UserFilled /></el-icon>{{ $t('用户查询') }}</span
                        >
                    </el-col>
                </el-row>
                <el-card>
                    <el-form :model="findform" :inline="true" label-width="100px">
                        <el-row :gutter="10">
                            <template v-for="(item, index) in Stores.comui[componentId][0].baseProps">
                                <el-col v-if="item.visible && item.ismore == false" :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
                                    <el-form-item :label="I(item.label, item.labeleng)">
                                        <template #default>
                                            <div v-if="item.type === 'date'">
                                                <el-date-picker v-model="findform[item.prop]" type="date" clearable style="width: 160px" :id="item.prop" />
                                            </div>
                                            <div v-if="item.prop === 'roleid'">
                                                <rolemodel v-model:name="findform['role']" v-model:id="findform['roleid']" :isreadonly="true"></rolemodel>
                                            </div>
                                            <div v-else>
                                                <el-input :readonly="item.readonly" v-model="findform[item.prop]" :id="item.prop" />
                                            </div>
                                        </template>
                                    </el-form-item>
                                </el-col>
                            </template>
                        </el-row>
                    </el-form>
                </el-card>
                <el-card>
                    <el-row style="padding: 5px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                        <el-col :span="4">
                            <span style="font-size: 20px; font-weight: 1000; color: white">
                                <el-icon><Grid /></el-icon>{{ $t('列表数据') }}
                            </span>
                        </el-col>
                        <el-col :span="20">
                            <el-button :loading="loading"  style="float: right" round type="primary" @click="savedata"> {{ $t('保存') }} </el-button>
                        </el-col>
                    </el-row>
                    <div v-for="(item, index) in tabledata" :key="index" >
                        <el-descriptions :title="item.name" :column="6" size="large" label-width="0">
                            <template #title>
                                <el-checkbox style="margin-left: 10px" v-model="item.select" @change="(event) => allselect(event, item.id)">
                                    <span style="font-size: 20px">{{ $t(item.name) }}</span>
                                </el-checkbox>
                            </template>
                            <template v-for="[key, operation] in Object.entries(item)">
                                <el-descriptions-item v-if="key !== 'id' && key !== 'name' && key !== 'path' && key !== 'select'" :key="key">
                                    <el-checkbox v-model="item[key].select" :label="$t(item[key].name)" size="large" />
                                </el-descriptions-item>
                            </template>
                        </el-descriptions>
                    </div>
                </el-card>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
//@ts-ignore
import { httpSend } from '@/utils/api';
import { GrantObj } from '@/utils/grantset';
import { useI18n } from 'vue-i18n';
import { getCurrentInstance, onMounted, ref, reactive, watch, computed } from 'vue';
import { Search } from '@element-plus/icons-vue';
import Menu from '@/assets/menu.json';
/*组件*/
import rolemodel from '@/components/share/rolemodel.vue';
//@ts-ignore
import { TableUiSection } from '@/components/share/ui-set.interface.ts';
//@ts-ignore
import { usegrantStore, useshareStore } from '@/store'; /*pina管理*/
import { chkgrant } from '@/globalmethods'; /*通用方法*/
const grantStore = usegrantStore() as any;
const { t } = useI18n(); //多语言
// 自定义字段配置
const componentId = 'permissionsetting';
const uiSectionList: TableUiSection[] = [
    {
        baseProps: [{ label: '角色', prop: 'roleid', visible: true, readonly: false, type: 'string', ismore: false }],
        tableProps: [
            { label: '选择', labelex: '', labeleng: '', prop: 'checked', visible: true, readonly: false, width: '80', type: 'checkbox', fixed: 'left', align: 'center' },
            { label: '功能分类', labelex: '', labeleng: '', prop: 'name', visible: true, readonly: false, width: '500', type: 'string', fixed: null, align: 'center' },
        ],
    },
];
const Stores = useshareStore() as any;
Stores.setcomui([componentId, uiSectionList]);
const { appContext } = getCurrentInstance();
const ElMessage = appContext.config.globalProperties.$ElMessage;
const loading = ref(false);
let tabledata: any = ref([]);
const findform = reactive({
    roleid: null,
    role: null,
    des: null,
});

//动态计算表格最大高度
const tableMaxHeight = computed(() => {
    return window.innerHeight - 350;
});
const defaultProps = {
    children: null, //只显示一层
    label: 'name',
};
//树节点设置
const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();
//输入栏过滤
watch(filterText, (val) => {
    treeRef.value!.filter(val);
});
const treedata: any = ref([]); //tree数据
//初始化
onMounted(() => {
    treedata.value = filterTree(Menu);
    // gettablelist();
});

let Allcheck = ref(false);
//表头全选/取消
const CheckAllChange = (val: boolean) => {
    tabledata.value.forEach((v) => {
        v.checked = val;
    });
    tabledata.value = [...tabledata.value];
};

const recordid = ref(null);
const menuid = ref(null);
const roleid = ref(null);
const channelids = ref(null);

//保存权限信息
const savedata = async () => {
    if (!chkgrant('权限管理', 'Grantsave')) {
        ElMessage.warning(t('您暂无修改权限,请联系管理员!'));
        return;
    }
    let data = {
        recordid: recordid.value,
        menuid: menuid.value,
        roleid: findform.roleid,
        channelids: channelids.value,
        functionlist: tabledata.value,
    };
    const fd = new FormData();
    fd.append('param', JSON.stringify(data));
    loading.value = true;
    try {
        const res = await httpSend('Grantsave', fd);
        if (res.code === 1) {
            gettablelist();
            loadgrant();
        } else {
            console.log('失败');
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};

// 过滤掉带有 visible: false 的节点
function filterTree(data) {
    return data.reduce((acc, node) => {
        if (node.visible) {
            let newNode = { ...node };
            if (newNode.children) {
                newNode.children = filterTree(newNode.children);
            }
            acc.push(newNode);
        }
        return acc;
    }, []);
}
// 一键展开
const expandAll = async () => {
    Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.expand());
};

// 一键收缩
const collapseAll = () => {
    Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.collapse());
};
//输入栏过滤
const filterNode = (value: string, data: any) => {
    if (!value) return true;
    return data.name.includes(value);
};

//点击当前节点
const handleNodeClick = (data, node) => {
    if (findform.roleid == null) {
        ElMessage.warning(t('请先选择角色'));
        return;
    }
    if (!chkgrant('权限管理', 'Grantfindlist')) {
        ElMessage.warning(t('您暂无查看权限,请联系管理员!'));
        return;
    }
    tabledata.value = [];
    menuid.value = data.id;
    if (GrantObj[data.id]) {
        tabledata.value = JSON.parse(JSON.stringify(GrantObj[data.id].list));
    } else {
        tabledata.value = [];
    }
    gettablelist();
};

//查询数据
const gettablelist = async () => {
    loading.value = true;
    let passarr = { id: 1, name: 1, path: 1, select: 1 };
    const fd = new FormData();
    let data = { menuid: menuid.value, roleid: findform.roleid };
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('Grantfindlist', fd, false);
    if (res && res.code == 1) {
        if (res.data && res.data.length > 0) {
            recordid.value = res.data[0]['id'];
            channelids.value = res.data[0]['channelids'];
            let data = JSON.parse(res.data[0]['functionlist']);
            //更新selct值
            copySelectValues(data, tabledata.value);
        } else {
            recordid.value = null;
            channelids.value = null;
        }
    }
    loading.value = false;
};

const copySelectValues = (source: any, target: any) => {
    const mapById = new Map<string, Item>();
    // 首先将 source 数组中的元素按 id 放入 map 中
    source.forEach((item) => {
        mapById.set(item.id, item);
    });
    // 遍历 target 数组并更新 select 值
    target.forEach((targetItem) => {
        const sourceItem = mapById.get(targetItem.id);
        if (sourceItem) {
            // 更新顶层 select 值
            targetItem.select = sourceItem.select;
            // 遍历每个操作项（如 getemployeelist, deleteemployee 等）
            for (const key in targetItem) {
                if (typeof targetItem[key] === 'object' && 'select' in targetItem[key]) {
                    const correspondingSourceOperation = sourceItem[key];
                    if (correspondingSourceOperation) {
                        targetItem[key].select = correspondingSourceOperation.select;
                    }
                }
            }
        }
    });
};

//全选
const allselect = (event, id) => {
    let passarr = { id: 1, name: 1, path: 1, select: 1 };
    for (let i = 0; i < tabledata.value.length; i++) {
        if (tabledata.value[i].id == id) {
            for (let key in tabledata.value[i]) {
                if (!passarr[key]) {
                    tabledata.value[i][key]['select'] = event;
                }
            }
        }
    }
};

//加载用户权限
const loadgrant = async () => {
    const res = await httpSend('loadgrant', {}, false);
    if (res.data) {
        grantStore.setisadmin(res.isadmin);
        grantStore.setgrantlist(res.data);
    }
};
const I = (label, labeleng) => {
    if (labeleng && localStorage.getItem('locale') == 'en') {
        return labeleng;
    }
    return t(label);
};
</script>

<style scope>
.el-descriptions__header {
    align-items: center;
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
    background-color: #d7d7d7;
}
.el-card__body {
    padding: 5px !important;
    color: #000000;
}
</style>
